const http = require('http');
const sqlite3 = require('sqlite3').verbose();
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');

// JWT密钥
const JWT_SECRET = 'your-secret-key';

// 创建数据库连接
const db = new sqlite3.Database('todo.db');

// 初始化数据库表
db.serialize(() => {
  // 用户表
  db.run(`CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE,
        password TEXT
    )`);

  // TODO表
  db.run(`CREATE TABLE IF NOT EXISTS todos (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER,
        content TEXT,
        completed INTEGER DEFAULT 0,
        FOREIGN KEY(user_id) REFERENCES users(id)
    )`);

  // 检查是否已存在 admin 用户
  db.get('SELECT id FROM users WHERE username = ?', ['admin'], (err, row) => {
    if (err) {
      console.error('Error checking admin user:', err);
      return;
    }

    // 如果 admin 用户不存在，则创建
    if (!row) {
      const hashedPassword = crypto.createHash('md5').update('ddd').digest('hex');
      db.run('INSERT INTO users (username, password) VALUES (?, ?)',
        ['admin', hashedPassword], (err) => {
          if (err) {
            console.error('Error creating admin user:', err);
          } else {
            console.log('Admin user created successfully');
          }
        });
    }
  });

  // 检查初始用户是否创建成功
  db.get('SELECT * FROM users WHERE username = ?', ['admin'], (err, row) => {
    if (err) {
      console.error('Error checking admin user:', err);
    } else {
      console.log('Current admin user:', row); // 这会显示用户信息
    }
  });
});

// 请求体解析
const getRequestBody = (req) => {
  return new Promise((resolve, reject) => {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      try {
        resolve(JSON.parse(body));
      } catch {
        resolve({});
      }
    });
  });
};

// 验证token
const verifyToken = (token) => {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch {
    return null;
  }
};

// 静态文件处理
const serveStaticFile = (filePath, res) => {
  const extname = path.extname(filePath);
  const contentTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css'
  };

  fs.readFile(filePath, (err, content) => {
    if (err) {
      res.writeHead(404);
      res.end('File not found');
      return;
    }

    res.writeHead(200, { 'Content-Type': contentTypes[extname] || 'text/plain' });
    res.end(content);
  });
};

// 创建服务器
const server = http.createServer(async (req, res) => {
  // 允许CORS
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }

  // 静态文件服务
  if (req.method === 'GET' && !req.url.startsWith('/api/')) {
    const filePath = req.url === '/' ? './index.html' : `.${req.url}`;
    serveStaticFile(filePath, res);
    return;
  }

  // API路由处理
  if (req.url === '/api/register' && req.method === 'POST') {
    const { username, password } = await getRequestBody(req);

    // 添加输入验证
    if (!username || !password) {
      res.writeHead(400, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ message: '用户名和密码不能为空' }));
      return;
    }

    const hashedPassword = crypto.createHash('md5').update(password).digest('hex');

    // 先检查用户名是否已存在
    db.get('SELECT id FROM users WHERE username = ?', [username], (err, row) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: '服务器错误' }));
        return;
      }

      if (row) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: '用户名已存在' }));
        return;
      }

      // 用户名不存在，执行注册
      db.run('INSERT INTO users (username, password) VALUES (?, ?)',
        [username, hashedPassword], function (err) {
          if (err) {
            console.error('Registration error:', err);
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ message: '注册失败，请稍后重试' }));
            return;
          }
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ message: '注册成功' }));
        });
    });
    return;
  }

  if (req.url === '/api/login' && req.method === 'POST') {
    const { username, password } = await getRequestBody(req);
    const hashedPassword = crypto.createHash('md5').update(password).digest('hex');

    console.log('Login attempt:', { username, hashedPassword });

    db.get('SELECT id FROM users WHERE username = ? AND password = ?',
      [username, hashedPassword], (err, row) => {
        if (err) {
          console.error('Login error:', err);
          res.writeHead(500, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ message: '服务器错误' }));
          return;
        }

        if (!row) {
          console.log('Login failed: Invalid credentials');
          res.writeHead(401, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ message: '用户名或密码错误' }));
          return;
        }

        console.log('Login successful for user:', username);
        const token = jwt.sign({ userId: row.id }, JWT_SECRET);
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ token }));
      });
    return;
  }

  // 验证token的中间件
  const token = req.headers.authorization?.split(' ')[1];
  const user = verifyToken(token);
  if (!user) {
    res.writeHead(401, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Unauthorized' }));
    return;
  }

  // TODO相关API
  if (req.url === '/api/todos' && req.method === 'GET') {
    db.all('SELECT * FROM todos WHERE user_id = ?', [user.userId], (err, rows) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(rows || []));
    });
  }
  else if (req.url === '/api/todos' && req.method === 'POST') {
    const { content } = await getRequestBody(req);
    db.run('INSERT INTO todos (user_id, content) VALUES (?, ?)',
      [user.userId, content], function (err) {
        if (err) {
          res.writeHead(400, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ message: 'Failed to create todo' }));
          return;
        }
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ id: this.lastID, content }));
      });
  }
  else if (req.url.startsWith('/api/todos/') && req.method === 'PUT') {
    const todoId = req.url.split('/')[3];
    const { content } = await getRequestBody(req);
    db.run('UPDATE todos SET content = ? WHERE id = ? AND user_id = ?',
      [content, todoId, user.userId], (err) => {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: 'Updated successfully' }));
      });
  }
  else if (req.url.startsWith('/api/todos/') && req.method === 'DELETE') {
    const todoId = req.url.split('/')[3];
    db.run('DELETE FROM todos WHERE id = ? AND user_id = ?',
      [todoId, user.userId], (err) => {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: 'Deleted successfully' }));
      });
  }
  else if (req.url === '/api/todos' && req.method === 'DELETE') {
    db.run('DELETE FROM todos WHERE user_id = ?', [user.userId], (err) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ message: 'All todos deleted' }));
    });
  }
  else if (req.url === '/api/debug' && req.method === 'GET') {
    // 只在开发环境使用
    db.all(`
        SELECT 
            todos.id,
            todos.content,
            todos.completed,
            users.username
        FROM todos 
        JOIN users ON todos.user_id = users.id
    `, [], (err, rows) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: err.message }));
        return;
      }
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(rows, null, 2));
    });
    return;
  }
  else {
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Not found' }));
  }
});

// 启动服务器
const PORT = 8080;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});
